package com.epb.eventpcb.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.epb.eventpcb.common.ServiceResult;
import com.epb.eventpcb.common.StatusEnum;
import com.epb.eventpcb.pojo.SysUser;
import com.epb.eventpcb.service.ISysUserService;
import com.epb.eventpcb.util.SessionContextUtils;
import com.epb.eventpcb.vo.LoginVo;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    ISysUserService userService;
    @Resource()
    private Producer producer;
    @Resource(name = "caffeineCodeCacheManager")
    CacheManager codeCacheManager;


    @PostMapping("/doLogin")
    public ServiceResult doLogin(@RequestBody LoginVo loginVo){
        Integer loginCode = codeCacheManager.
                getCache("codeCache")
                .get(loginVo.getCodeKey(),Integer.class);
        if(loginCode==null ||
                !loginCode.equals(loginVo.getCode())){
            return ServiceResult.buildFail(StatusEnum.ERROR.getStatus(),
                    "验证码错误");
        }
        if(StringUtils.isEmpty(loginVo.getUsername())
            || StringUtils.isEmpty(loginVo.getPassword())){
            return ServiceResult.buildFail(StatusEnum.ERROR.getStatus(),
                    "账号/密码错误");
        }
        List<SysUser> userList =
                userService.getUserByUsername(loginVo.getUsername());
        if(userList==null || userList.size()==0) {
            return ServiceResult.buildFail(StatusEnum.ERROR.getStatus(),
                    "账号/密码错误");
        }
        SysUser sysUser = userList.get(0);
        if(!sysUser.getPassword().equals(loginVo.getPassword())){
            return ServiceResult.buildFail(StatusEnum.ERROR.getStatus(),
                    "账号/密码错误");
        }
        StpUtil.login(sysUser.getId());
        return ServiceResult.buildSuccess(sysUser);
    }


    @GetMapping("vrfctnCode.jpg")
    public ServiceResult vrfctnCode(HttpServletRequest request,
                                    HttpServletResponse response) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String sessionId = request.getSession().getId();
        String text = userService.getLoginCode(sessionId);
        //个位数字相加
        String s1 = text.substring(0, 1);
        String s2 = text.substring(1, 2);
        int count = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
        codeCacheManager.getCache("codeCache").put(sessionId, count);
        //生成图片验证码
        BufferedImage image = producer.createImage(s1 + "+" + s2 + "=?");
        try {
            ImageIO.write(image, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "")
                .replaceAll("\r", "");//删除 \r\n
        Map<String,String> map = new HashMap<String,String>();
        map.put("base64Url", "data:image/jpg;base64," + png_base64);
        map.put("key", sessionId);
        return ServiceResult.buildSuccess(map);
    }

}
